package cn.tedu.wallet.service.rabbitMQ;

import cn.tedu.wallet.config.RabbitConfiguration;
import cn.tedu.wallet.consts.TradeStatus;
import cn.tedu.wallet.dao.repository.RecordRepository;
import cn.tedu.wallet.pojo.po.RecordMQPO;
import cn.tedu.wallet.pojo.po.UserTransactionRecordPO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class RabbitMQRecordConsumer {

    @Autowired
    private RecordRepository recordRepository;

    @RabbitListener(queues = RabbitConfiguration.DEAD_LETTER_QUEUE_NAME)
    public void consumeRecordQueue (RecordMQPO recordMQPO, Message message, Channel channel){
        log.debug("消费死信队列消息:{}",recordMQPO);

        log.debug("消费者调用数据库检查交易状态");
        UserTransactionRecordPO recordPO = recordRepository.getRecordDetail(recordMQPO.getRecordId());
        log.debug("当前记录状态:{}",recordPO);
        if (recordPO.getTransactionStatus().equals(TradeStatus.ONGOING.getCode())) {
            log.debug("交易状态为进行中,更新记录状态为撤销");
            recordPO.setTransactionStatus(TradeStatus.CANCELED.getCode());
            recordRepository.updateRecord(recordPO);
        }else {
            log.debug("交易状态已更新过,无需更新");
        }


        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            channel.basicAck(deliveryTag,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
